package com.ktjy.controller;

import com.ktjy.entity.SysUser;
import com.ktjy.service.SysUserService;
import com.ktjy.utils.Constants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author 黄军艳
 * @version 1.0
 * @date 2024/12/16  9:44
 */
@Controller
public class LoginController extends BaseController {
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/login")
    public String toLogin() {
        return forward("/login.jsp");
    }

    @PostMapping(value = "/login")
    public String login(@RequestParam("account") String account,
                        @RequestParam("password") String password,
                        HttpServletRequest request,
                        HttpSession session){
        //调用service方法，进行用户匹配
        SysUser loginUser= sysUserService.login(account,password);
        if(loginUser!=null){ //登录成功
            session.setAttribute(Constants.SESSION_USER,loginUser);
            //重定向到后台首页
            return redirect("/main/index");
        }else {
            request.setAttribute(Constants.REQUEST_ERROR,"用户名或密码错误！");
            return forward("/login.jsp");
        }
    }

    /**
     * 退出登录
     */
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return redirect("/login.jsp");
    }

    //跳转到后台首页
    @GetMapping("/main/index")
    public String index(){
        return "index";
    }
}
